package com.huitong.gateway.filter;

import cn.dev33.satoken.SaManager;
import cn.dev33.satoken.same.SaSameUtil;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import static cn.dev33.satoken.same.SaSameUtil.SAME_TOKEN;

/**
 * 转发认证过滤器 内部服务外网隔离
 *
 * @author fromdrowning
 * @date 2024/3/17 13:09
 */
@Component
public class ForwardAuthFilter implements GlobalFilter, Ordered {

    /**
     * 为请求头添加SA-SAME-TOKEN供内部服务鉴权
     *
     * @param exchange 当前请求和响应的信息
     * @param chain    过滤器链
     * @return 响应式对象
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 未开启配置则直接跳过
        if (!SaManager.getConfig().getCheckSameToken()) {
            return chain.filter(exchange);
        }

        // 为请求头添加SA-SAME-TOKEN
        ServerHttpRequest newRequest = exchange.getRequest()
            .mutate()
            .header(SAME_TOKEN, SaSameUtil.getToken())
            .build();

        return chain.filter(exchange.mutate()
            .request(newRequest)
            .build());
    }

    /**
     * 设置优先级
     *
     * @return 优先级
     */
    @Override
    public int getOrder() {
        return -100;
    }
}
